##########################################################################################

library(data.table)
library(optparse)
library(dplyr)
library(RColorBrewer)
library(ggpubr)

##########################################################################################

option_list <- list(
    make_option(c("--gene_list"), type = "character") ,
    make_option(c("--ccf_file"), type = "character") ,
    make_option(c("--sample_info"), type = "character") ,
    make_option(c("--class_order_file"), type = "character") ,
    make_option(c("--out_path"), type = "character")
)

if(1!=1){
    
    ccf_file <- "~/20220915_gastric_multiple/dna_combine/mutationTime/result/All_CCF_mutTime.addShare.tsv"
    sample_info <- "~/20220915_gastric_multiple/dna_combine/config/tumor_normal.class.list"
    gene_list <- "~/20220915_gastric_multiple/dna_combine/public_ref/importTantGene.list"
    out_path <- "~/20220915_gastric_multiple/dna_combine/images/DriverEverySample"
    class_order_file <- "~/20220915_gastric_multiple/dna_combine/config/Class_order_sub.list"

}

###########################################################################################

parseobj <- OptionParser(option_list=option_list, usage = "usage: Rscript %prog [options]")
opt <- parse_args(parseobj)
print(opt)

gene_list <- opt$gene_list
ccf_file <- opt$ccf_file
sample_info <- opt$sample_info
out_path <- opt$out_path
class_order_file <- opt$class_order_file

###########################################################################################

dir.create(out_path , recursive = T)

###########################################################################################

dat_mutiNodule <- data.frame(fread(ccf_file))
dat_info <- data.frame(fread(sample_info))
dat_gene <- data.frame(fread(gene_list))
class_a_order <- data.frame(fread(class_order_file))

###########################################################################################

Variant_Type <- c("Missense_Mutation","Nonsense_Mutation","Frame_Shift_Ins","Frame_Shift_Del","In_Frame_Ins","In_Frame_Del","Splice_Site","Nonstop_Mutation")

###########################################################################################

dat_mutiNodule$Location <- paste0( 
    dat_mutiNodule$Hugo_Symbol , "\n"  , dat_mutiNodule$Variant_Classification , "\n" , 
    dat_mutiNodule$Chr , ":" , dat_mutiNodule$Start_Position , ":" ,
    dat_mutiNodule$REF , ":" , dat_mutiNodule$ALT , ":"   )

#dat_mutiNodule_msi$Location <- paste0( 
#    dat_mutiNodule_msi$Hugo_Symbol , "\n"  , dat_mutiNodule_msi$Variant_Classification , "\n" , 
#    dat_mutiNodule_msi$Chr , ":" , dat_mutiNodule_msi$Start_Position , ":" ,
#    dat_mutiNodule_msi$REF , ":" , dat_mutiNodule_msi$ALT , ":"   )

#dat_mutiNodule <- rbind( dat_mutiNodule_msi , dat_mutiNodule )

###########################################################################################

col <- c(
  brewer.pal(9,"YlGnBu")[6],
  rgb(234,106,79,alpha=255,maxColorValue=255),
  rgb(203,24,30,alpha=255,maxColorValue=255),
  rgb(255,0,0,alpha=255,maxColorValue=255)
  )

names(col) <- c("IM" , "IGC" , "DGC" , "GC")

###########################################################################################
## Function
plotVAF <- function( tmp = tmp  , Normal = Normal , out_path = out_path , col = col ) {

    dat_ccf_use <- tmp
    dat_ccf_use$CLS <- gsub( "[[]" , "\n[" , dat_ccf_use$CLS )
    dat_ccf_use$majorCN <- dat_ccf_use$total_cn - dat_ccf_use$minor_cn
    dat_ccf_use$cnv_txt <- paste0( "TCN:" , dat_ccf_use$total_cn , "\nLCN:" , dat_ccf_use$minor_cn , "\n" , "MCN:" , dat_ccf_use$MutCN )
    dat_ccf_use$cnv_color <- "black"
    dat_ccf_use$cnv_color <- ifelse( dat_ccf_use$total_cn > 2 , "red" , dat_ccf_use$cnv_color )
    dat_ccf_use$cnv_color <- ifelse( dat_ccf_use$total_cn < 2 , "blue" , dat_ccf_use$cnv_color )
    dat_ccf_use$cnv_color <- ifelse( dat_ccf_use$minor_cn == 0 & dat_ccf_use$total_cn == 2 , "DarkGreen" , dat_ccf_use$cnv_color )
    dat_ccf_use$class_y <- ifelse( dat_ccf_use$CLS == "Subclonal" , dat_ccf_use$CCF_adj + 0.1 , 1.6 )

    cnv_color <- c("red" , "black" , "blue" , "DarkGreen")
    names(cnv_color) <- cnv_color

    plot <- ggplot(dat_ccf_use,aes(x=Class_sub,y=CCF_adj,fill=Class)) + geom_bar(position="dodge",stat="identity") + 
        ylab(paste0(Normal,"  CCF")) +
        theme_bw() +
        ylim(0,1.6) +
        scale_fill_manual(values=c(col)) +
        geom_text(mapping = aes(x = Class_sub , y = class_y , label = CLS) , size= 4.5 , face='bold' , color="black") +
        geom_text(mapping = aes(x = Class_sub , y = 1.3 , label = cnv_txt , color = cnv_color ) , size=3.5 , face='bold') +
        scale_color_manual(values=cnv_color) +
        theme(panel.background = element_rect(fill = NA, colour = "black", size = 1),
        legend.position ='none',
        legend.title = element_blank() ,
        panel.grid.major = element_line(colour=NA),
        legend.text = element_text(size = 10,color="black",face='bold'),
        axis.text.x = element_text(size = 10 , color="black",face='bold'),
        axis.text.y = element_text(size = 15,color="black",face='bold'),
        axis.title.x = element_text(size = 10,color="black",face='bold'),
        axis.title.y = element_text(size = 10,color="black",face='bold'),
        axis.line = element_line(size = 0.5)) +
        facet_grid(.~Location,space='free_x',scales='free_x') +
        theme(strip.text.x = element_text(size = 8,color="black",face='bold'))

    out_name <- paste0(out_path , "/" , Normal , "_Driver.pdf")
    ggsave(file=out_name,plot=plot,width= ( 3 + length(unique(tmp$Location)) + length(unique(tmp$Tumor)) ), height=6 , limitsize = FALSE)

}

###########################################
for( Sample in unique(dat_info$ID) ){
    print(Sample)
    tumors <- subset( dat_info , ID == Sample )$Tumor
    tmp <- subset( dat_mutiNodule , Sample %in% tumors & Variant_Classification %in% Variant_Type & Hugo_Symbol %in% dat_gene$Gene_Symbol )

    tmp <- merge( tmp , dat_info[,c("Tumor" , "Class_sub")] , by.y = "Tumor" , by.x = "Sample" )
    tmp$Class_sub <- factor( tmp$Class_sub , levels = class_a_order$Class , order = T ) 

    if(nrow(tmp) > 0){
        plotVAF( tmp = tmp  , Normal = Sample , out_path = out_path , col = col )
    }
   
}